package com.lv.suyiyong.hfr.fragment

import android.Manifest
import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.service.adapter.ViewPager2ComAdapter
import com.lv.service.bean.TelSecondCategory
import com.lv.service.dialog.CategoryImagePopupView
import com.lv.service.model.EditorViewModel
import com.lv.service.room.category.CategoryBean
import com.lv.service.room.category.CategoryDbHelper
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.FragmentHomeFactoryBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


/**
 * 作者： ygx
 * 创建日期：2023/2/10 11:24 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：应用商城需要的权限：ABCDEFGHIJKLMNO
 */
class HomeFactoryFragment : BaseFragment(), View.OnClickListener {
    private val mCategoryBeans = mutableListOf<CommonSelectedBean>()
    private val mCategoryPopBeans = mutableListOf<TelSecondCategory>()
    private var mTabAdapter: ViewPager2ComAdapter? = null
    private val mEditorViewModel: EditorViewModel by activityViewModels()
    private var mBinding: FragmentHomeFactoryBinding? = null
    private var mFcaid = 0

    override fun getLayoutRes() = R.layout.fragment_home_factory
    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentHomeFactoryBinding.bind(view).apply {
            ivMore.setOnClickListener(this@HomeFactoryFragment)
        }

        return mBinding!!
    }

    override fun initConfig() {
        super.initConfig()
//        lifecycleScope.launchWhenCreated {
//            val taskCategory = async {
//                val mCategorys = getCategoryForDB()
//                mCategoryBeans.clear()
//                mCategoryBeans.add(CommonSelectedBean("推荐工厂", "", true))
//                mCategorys?.forEach { categoryItem ->
//                    mCategoryBeans.add(
//                        CommonSelectedBean(
//                            categoryItem.name,
//                            "${categoryItem.fcaid}"
//                        )
//                    )
//                }
//            }
//            taskCategory.await()
//            initPage()
//        }
        mEditorViewModel.liveCategoryData.observeKt { mCategorys ->
            mCategoryBeans.clear()
            mCategoryPopBeans.clear()
            mCategoryBeans.add(CommonSelectedBean("推荐工厂", "", true))
            mCategorys?.forEach { categoryItem ->
                val telSecondCategory = TelSecondCategory(
                    categoryItem.fcaid, categoryItem.id, categoryItem.image, categoryItem.name,
                    0, 0, null, false, true
                )
                mCategoryPopBeans.add(telSecondCategory)
                mCategoryBeans.add(
                    CommonSelectedBean(
                        categoryItem.name,
                        "${categoryItem.fcaid}"
                    )
                )
                val telSecondCategories = categoryItem.telSecondCategories
                telSecondCategories?.let { mCategoryPopBeans.addAll(it) }
            }
            initPage()
        }

        /*// 获取定位信息后的回调，
        locationUtil.locationCallBack = {
            val address = locationUtil.getAddress(requireContext(), it)
            try {
                val city = "${address?.locality}"
//                val town = address?.getAddressLine(0)
                var featureName = address?.featureName
                if (featureName.isNullOrEmpty()) {
                    featureName = address?.thoroughfare + address?.subThoroughfare
                }
                SPStaticUtils.put(Constants.ADDRESS_CITY_RECEIPT_KEY, city)
                SPStaticUtils.put(Constants.ADDRESS_TOWN_RECEIPT_KEY, featureName)
            } catch (e: Exception) {
            }
        }*/
//        UserDbHelper.getLiveUserInfo(requireContext()).observeKt { userInfo ->
//            if (userInfo != null && userInfo.id.isNotEmpty()) {
//                mUserInfo = userInfo
//
//            }
//        }


    }

    private fun initPage() {
        initViewPager()
    }

    private fun initViewPager() {

        mTabAdapter = ViewPager2ComAdapter(
            childFragmentManager, lifecycle, mCategoryBeans,
            object : ViewPager2ComAdapter.TabPagerListener {
                override fun getFragment(position: Int): Fragment {
                    return HomeCategoryFragment.newInstance(mCategoryBeans[position])
                }

            }
        )
        mBinding?.viewPager?.adapter = mTabAdapter
        mBinding?.viewPager?.offscreenPageLimit = mCategoryBeans.size

        mBinding?.ygxIndicator?.setViewPager(mBinding?.viewPager, mCategoryBeans)
        mBinding?.ygxIndicator?.setOnPageChangeListener(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                var fac = mCategoryBeans[position].tag
                if (fac.isEmpty()) {
                    fac = "0"
                }
                try {
                    mFcaid = fac.toDouble().toInt()
                } catch (e: Exception) {
                    mFcaid = 0
                }
            }
        })

    }


    private suspend fun getCategoryForDB(): List<CategoryBean>? {
        return withContext(Dispatchers.IO) {
            //所有厂家分类
            CategoryDbHelper.getFindAllCategorySuspend(requireContext())
        }
    }

    override fun initData() {
        super.initData()

    }


    override fun initEvents() {
        super.initEvents()

//        rigestEventBus()
    }

    private fun checkPermissionLoction() {
        val permissions = mutableListOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
        )
        // 用于在您浏览、搜索或参与特定活动时，向您展示当前城市服务信息，以提升体验。不申请该权限不影响APP的正常使用。是否同意去申请该权限？
        PermissionXUtils.checkPermissBefore(
            this,
            permissions,
            "上传回执需要授予位置权限，用于展示当前城市的服务信息，以提升体验。不申请该权限不影响APP的正常使用。",
            object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>,
                ) {
                    if (allGranted) {
//                        locationUtil.initLocationManager()
//                        LocationUtils.getInstance().getLocations(requireContext())

                    }

                }

                override fun fotPermsission() {

                }


            },
        )
    }


//    private fun rigestEventBus() {
//        LiveEventBus.get(
//            HomeRefreshEvent::class.java,
//        ).observe(
//            this
//        ) { s ->
//            if (s != null) {
//                val message = s.message
//                val offlineMessageBean = s.offlineMessage
//                val pushMessage = s.pushMessage
//                if (message != null) {
//                    val conversationID = message.conversationID
//                    val unreadCount = message.unreadCount
//                    mTvMsgTotalUnread?.text = "$unreadCount"
//                    mTvMsgTotalUnread?.visibility = if (unreadCount > 0) View.VISIBLE else View.GONE
//                    if (conversationID.contains("syy0000")) {
//                        if (conversationID == Constants.ID_TZ) {
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        } else if (conversationID == Constants.ID_FW) {
//                            ARouter.getInstance().build(ARoutUtils.MessageVisitRecodeActivity)
//                                .navigation()
//                        } else if (conversationID == Constants.ID_HD) {
//                            ARouter.getInstance().build(ARoutUtils.MessageInteractionActivity)
//                                .navigation()
//                        }
//
//                    } else {
//                        mTvMessageText?.text = "新增聊天消息"
//                        mViewChatBg?.setOnClickListener {
//                            //点击后，页面切换到消息Tab
//                            val showName = message.showName
//                            TUIUtils.startChat(
//                                conversationID,
//                                showName,
//                                V2TIMConversation.V2TIM_C2C
//                            )
//                        }
//                    }
//                    mIvMore?.visibility = View.VISIBLE
//                }
//                if (offlineMessageBean != null) {
//                    if (offlineMessageBean.action == OfflineMessageBean.REDIRECT_ACTION_CHAT) {
//                        if (TextUtils.isEmpty(offlineMessageBean.sender)) {
//                            return@observe
//                        }
//                        TUIUtils.startChat(
//                            offlineMessageBean.sender,
//                            offlineMessageBean.nickname,
//                            offlineMessageBean.chatType
//                        )
//                    }
//                }
//                if (pushMessage != null) {
//                    when (pushMessage.t) {
//                        "100" -> {//完善信息
//                            mTvMessageText?.text = "重要通知"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "102" -> {//书刊上新
//                            mTvMessageText?.text = "书刊上新"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "103" -> {// 商品风险下架
//                            mTvMessageText?.text = "商品风险下架"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "104" -> {// 货圈风险下架
//                            mTvMessageText?.text = "货圈风险下架"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//
//                        }
//                        "105" -> {// 货圈审核通过
//                            mTvMessageText?.text = "审核通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "106" -> {// 106 货圈审核未通过
//                            mTvMessageText?.text = "审核未通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//
//                        "107" -> {// 商品上架通过
//                            mTvMessageText?.text = "审核通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "108" -> {// 商品上架拒绝
//                            mTvMessageText?.text = "审核未通过"
//                            ARouter.getInstance().build(ARoutUtils.MessageTransActivity)
//                                .navigation()
//                        }
//                        "110" -> {// 访问消息
//                            ARouter.getInstance().build(ARoutUtils.MessageVisitRecodeActivity)
//                                .navigation()
//                        }
//                        "111", "112", "113", "114" -> {// 111 点赞货圈 112 关注店铺 113  收藏商品 114  拨打电话
//                            ARouter.getInstance().build(ARoutUtils.MessageInteractionActivity)
//                                .navigation()
//                        }
//                        else -> {
//
//                        }
//                    }
//                }
//
//            }
//        }
//    }
//    override fun isHaveHeadMargin(): Boolean {
//        return false
//    }

    companion object {
        @JvmStatic
        fun newInstance() = HomeFactoryFragment()
    }

    override fun onResume() {
        super.onResume()
        LogUtils.e("onResume")
//        initStatusBar(requireActivity(), true, false)
    }

//    override fun onHiddenChanged(hidden: Boolean) {
//        super.onHiddenChanged(hidden)
//        LogUtils.e("onHiddenChanged==$hidden")
//        if (!hidden) {
//            initStatusBar(requireActivity(), true, false)
//        }
//    }


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_more -> {
                showCategoryPop()
            }
        }
    }

    //    private var mCategoryPopupView: CategoryImagePopupView? = null
    private fun showCategoryPop() {
        val topH = SizeUtils.dp2px(200.0f)
        var mCategoryPopupView = CategoryImagePopupView(
            requireContext(), "全部分类", mCategoryPopBeans, topH,
            { position, datas -> })
        XPopup.Builder(requireContext())
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个true
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mCategoryPopupView)
            .show()
        mCategoryPopupView.scrollID(mFcaid)
    }


//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (data != null) {
//            //QQ回调
//            ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
//        }
//    }
}